package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.MaintenanceReminder;
import com.vehiclemanagement.entity.Vehicle;
import com.vehiclemanagement.mapper.MaintenanceReminderMapper;
import com.vehiclemanagement.mapper.VehicleMapper;
import com.vehiclemanagement.service.MaintenanceReminderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 车辆维修保养提醒服务实现类
 */
@Service
@Slf4j
public class MaintenanceReminderServiceImpl extends ServiceImpl<MaintenanceReminderMapper, MaintenanceReminder> implements MaintenanceReminderService {

    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public IPage<MaintenanceReminder> pageMaintenanceReminders(Integer current, Integer size, String searchTerm,
                                                            Long vehicleId, Integer reminderType, Integer status,
                                                            LocalDate startTime, LocalDate endTime) {
        // 创建分页对象
        Page<MaintenanceReminder> page = new Page<>(current, size);
        
        // 构建查询条件
        LambdaQueryWrapper<MaintenanceReminder> wrapper = new LambdaQueryWrapper<>();
        
        // 添加删除标记条件
        wrapper.eq(MaintenanceReminder::getDelFlag, 0);
        
        // 添加车辆ID条件
        if (vehicleId != null) {
            wrapper.eq(MaintenanceReminder::getVehicleId, vehicleId);
        }
        
        // 添加提醒类型条件
        if (reminderType != null) {
            wrapper.eq(MaintenanceReminder::getReminderType, reminderType);
        }
        
        // 添加状态条件
        if (status != null) {
            wrapper.eq(MaintenanceReminder::getStatus, status);
        }
        
        // 添加日期范围条件
        if (startTime != null && endTime != null) {
            wrapper.between(MaintenanceReminder::getReminderDate, startTime, endTime);
        } else if (startTime != null) {
            wrapper.ge(MaintenanceReminder::getReminderDate, startTime);
        } else if (endTime != null) {
            wrapper.le(MaintenanceReminder::getReminderDate, endTime);
        }
        
        // 添加搜索条件
        if (StringUtils.hasText(searchTerm)) {
            // 获取匹配车牌号的车辆ID列表
            List<Vehicle> vehicles = vehicleMapper.selectList(
                    new LambdaQueryWrapper<Vehicle>()
                            .like(Vehicle::getPlateNumber, searchTerm)
                            .eq(Vehicle::getDelFlag, 0)
            );
            List<Long> vehicleIds = vehicles.stream().map(Vehicle::getId).collect(Collectors.toList());
            
            if (!vehicleIds.isEmpty()) {
                wrapper.and(w -> w.like(MaintenanceReminder::getReminderContent, searchTerm)
                        .or()
                        .in(MaintenanceReminder::getVehicleId, vehicleIds));
            } else {
                wrapper.like(MaintenanceReminder::getReminderContent, searchTerm);
            }
        }
        
        // 按创建时间降序排序
        wrapper.orderByDesc(MaintenanceReminder::getCreateTime);
        
        // 执行分页查询
        IPage<MaintenanceReminder> resultPage = this.page(page, wrapper);
        
        // 填充车辆信息及其他名称字段
        if (resultPage.getRecords() != null && !resultPage.getRecords().isEmpty()) {
            for (MaintenanceReminder reminder : resultPage.getRecords()) {
                fillVehicleInfo(reminder);
                setReminderTypeName(reminder);
                setStatusName(reminder);
                setFrequencyName(reminder);
            }
        }
        
        return resultPage;
    }

    @Override
    public MaintenanceReminder getMaintenanceReminderById(Long id) {
        MaintenanceReminder reminder = this.getById(id);
        if (reminder != null) {
            fillVehicleInfo(reminder);
            setReminderTypeName(reminder);
            setStatusName(reminder);
            setFrequencyName(reminder);
        }
        return reminder;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMaintenanceReminder(MaintenanceReminder reminder) {
        // 设置初始状态
        if (reminder.getStatus() == null) {
            reminder.setStatus(0); // 未处理
        }
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        reminder.setCreateTime(now);
        reminder.setUpdateTime(now);
        
        // 设置删除标记
        reminder.setDelFlag(0);
        
        return this.save(reminder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMaintenanceReminder(MaintenanceReminder reminder) {
        // 设置更新时间
        reminder.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(reminder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMaintenanceReminder(Long id) {
        // 逻辑删除
        MaintenanceReminder reminder = new MaintenanceReminder();
        reminder.setId(id);
        reminder.setDelFlag(1);
        reminder.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(reminder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReminderStatus(Long id, Integer status) {
        MaintenanceReminder reminder = new MaintenanceReminder();
        reminder.setId(id);
        reminder.setStatus(status);
        reminder.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(reminder);
    }

    @Override
    public int countPendingReminders() {
        LambdaQueryWrapper<MaintenanceReminder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MaintenanceReminder::getDelFlag, 0)
                .eq(MaintenanceReminder::getStatus, 0) // 未处理
                .eq(MaintenanceReminder::getIsActive, true) // 启用状态
                .le(MaintenanceReminder::getReminderDate, LocalDate.now()); // 今天或之前的日期
        
        return (int) this.count(wrapper);
    }

    @Override
    public List<MaintenanceReminder> getMaintenanceRemindersByVehicleId(Long vehicleId) {
        LambdaQueryWrapper<MaintenanceReminder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MaintenanceReminder::getDelFlag, 0)
                .eq(MaintenanceReminder::getVehicleId, vehicleId)
                .eq(MaintenanceReminder::getIsActive, true)
                .orderByAsc(MaintenanceReminder::getReminderDate);
        
        List<MaintenanceReminder> reminders = this.list(wrapper);
        
        // 填充额外信息
        for (MaintenanceReminder reminder : reminders) {
            fillVehicleInfo(reminder);
            setReminderTypeName(reminder);
            setStatusName(reminder);
            setFrequencyName(reminder);
        }
        
        return reminders;
    }

    @Override
    public List<MaintenanceReminder> getUpcomingReminders(Integer days) {
        // 计算目标日期范围
        LocalDate today = LocalDate.now();
        LocalDate targetDate = today.plusDays(days);
        
        LambdaQueryWrapper<MaintenanceReminder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MaintenanceReminder::getDelFlag, 0)
                .eq(MaintenanceReminder::getStatus, 0) // 未处理
                .eq(MaintenanceReminder::getIsActive, true) // 启用状态
                .between(MaintenanceReminder::getReminderDate, today, targetDate)
                .orderByAsc(MaintenanceReminder::getReminderDate);
        
        List<MaintenanceReminder> reminders = this.list(wrapper);
        
        // 填充额外信息
        for (MaintenanceReminder reminder : reminders) {
            fillVehicleInfo(reminder);
            setReminderTypeName(reminder);
            setStatusName(reminder);
            setFrequencyName(reminder);
        }
        
        return reminders;
    }

    @Override
    public List<MaintenanceReminder> getOverdueReminders() {
        LocalDate today = LocalDate.now();
        
        LambdaQueryWrapper<MaintenanceReminder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MaintenanceReminder::getDelFlag, 0)
                .eq(MaintenanceReminder::getStatus, 0) // 未处理
                .eq(MaintenanceReminder::getIsActive, true) // 启用状态
                .lt(MaintenanceReminder::getReminderDate, today) // 早于今天的日期
                .orderByAsc(MaintenanceReminder::getReminderDate);
        
        List<MaintenanceReminder> reminders = this.list(wrapper);
        
        // 填充额外信息
        for (MaintenanceReminder reminder : reminders) {
            fillVehicleInfo(reminder);
            setReminderTypeName(reminder);
            setStatusName(reminder);
            setFrequencyName(reminder);
        }
        
        return reminders;
    }

    @Override
    public List<Map<String, Object>> getVehiclesExceedingMileageThreshold() {
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 获取所有按里程提醒的记录
        LambdaQueryWrapper<MaintenanceReminder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MaintenanceReminder::getDelFlag, 0)
                .eq(MaintenanceReminder::getStatus, 0) // 未处理
                .eq(MaintenanceReminder::getIsActive, true) // 启用状态
                .eq(MaintenanceReminder::getFrequency, "mileage") // 按里程提醒
                .isNotNull(MaintenanceReminder::getMileageThreshold);
        
        List<MaintenanceReminder> mileageReminders = this.list(wrapper);
        
        // 遍历提醒记录，检查车辆里程是否超过阈值
        for (MaintenanceReminder reminder : mileageReminders) {
            if (reminder.getVehicleId() != null && reminder.getMileageThreshold() != null) {
                Vehicle vehicle = vehicleMapper.selectById(reminder.getVehicleId());
                
                if (vehicle != null && vehicle.getCurrentMileage() != null 
                        && vehicle.getCurrentMileage() >= reminder.getMileageThreshold()) {
                    // 车辆里程已超过阈值，添加到结果集
                    Map<String, Object> item = new HashMap<>();
                    item.put("vehicleId", vehicle.getId());
                    item.put("plateNumber", vehicle.getPlateNumber());
                    item.put("currentMileage", vehicle.getCurrentMileage());
                    item.put("reminderId", reminder.getId());
                    item.put("reminderType", reminder.getReminderType());
                    item.put("reminderTypeName", getReminderTypeName(reminder.getReminderType()));
                    item.put("reminderContent", reminder.getReminderContent());
                    item.put("mileageThreshold", reminder.getMileageThreshold());
                    
                    result.add(item);
                }
            }
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processReminder(Long id, Integer status, String remark) {
        if (status != 1 && status != 2) {
            throw new IllegalArgumentException("状态值无效，只能是1（已处理）或2（已忽略）");
        }
        
        MaintenanceReminder reminder = new MaintenanceReminder();
        reminder.setId(id);
        reminder.setStatus(status);
        
        if (StringUtils.hasText(remark)) {
            reminder.setRemark(remark);
        }
        
        reminder.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(reminder);
    }

    @Override
    public List<Map<String, Object>> countRemindersByType() {
        QueryWrapper<MaintenanceReminder> wrapper = new QueryWrapper<>();
        wrapper.select("reminder_type, count(*) as count")
                .eq("del_flag", 0)
                .eq("is_active", true)
                .groupBy("reminder_type");
        
        List<Map<String, Object>> result = this.listMaps(wrapper);
        
        // 添加类型名称
        for (Map<String, Object> item : result) {
            Integer type = (Integer) item.get("reminder_type");
            item.put("reminderTypeName", getReminderTypeName(type));
        }
        
        return result;
    }

    /**
     * 填充车辆信息
     */
    private void fillVehicleInfo(MaintenanceReminder reminder) {
        if (reminder.getVehicleId() != null) {
            Vehicle vehicle = vehicleMapper.selectById(reminder.getVehicleId());
            if (vehicle != null) {
                reminder.setPlateNumber(vehicle.getPlateNumber());
            }
        }
    }

    /**
     * 设置提醒类型名称
     */
    private void setReminderTypeName(MaintenanceReminder reminder) {
        if (reminder.getReminderType() != null) {
            reminder.setReminderTypeName(getReminderTypeName(reminder.getReminderType()));
        }
    }

    /**
     * 获取提醒类型名称
     */
    private String getReminderTypeName(Integer type) {
        if (type == null) {
            return "";
        }
        
        switch (type) {
            case 1: return "定期保养";
            case 2: return "年检提醒";
            case 3: return "轮胎更换";
            case 4: return "机油更换";
            case 5: return "滤芯更换";
            case 6: return "其他";
            default: return "未知类型";
        }
    }

    /**
     * 设置状态名称
     */
    private void setStatusName(MaintenanceReminder reminder) {
        if (reminder.getStatus() != null) {
            switch (reminder.getStatus()) {
                case 0:
                    reminder.setStatusName("未处理");
                    break;
                case 1:
                    reminder.setStatusName("已处理");
                    break;
                case 2:
                    reminder.setStatusName("已忽略");
                    break;
                default:
                    reminder.setStatusName("未知状态");
            }
        }
    }

    /**
     * 设置频率名称
     */
    private void setFrequencyName(MaintenanceReminder reminder) {
        if (reminder.getFrequency() != null) {
            switch (reminder.getFrequency()) {
                case "once":
                    reminder.setFrequencyName("一次性");
                    break;
                case "daily":
                    reminder.setFrequencyName("每天");
                    break;
                case "weekly":
                    reminder.setFrequencyName("每周");
                    break;
                case "monthly":
                    reminder.setFrequencyName("每月");
                    break;
                case "quarterly":
                    reminder.setFrequencyName("每季度");
                    break;
                case "yearly":
                    reminder.setFrequencyName("每年");
                    break;
                case "mileage":
                    reminder.setFrequencyName("按里程");
                    break;
                default:
                    reminder.setFrequencyName("未知频率");
            }
        }
    }
} 